package com.browan.freepp.android.util;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.text.TextUtils;

public class DbHelper {

	private static final String DATABASE_CREATE_SYNC = "create table sync_table (_sync_id text primary key, value text not null);";
	private  static final String SYNC_ID = "_sync_id";
	private  static final String VALUE = "value";
	private  static final String TABLE_NAME = "sync_table";
	private static final String DATABASE_NAME = "sync.db";
	private static final int DATABASE_VERSION = 1;

	private DataBase help;
	private SQLiteDatabase mDb;
	private Context mContext;

	public DbHelper(Context c) {
		this.mContext = c;
	}
	
	private class DataBase extends SQLiteOpenHelper {

		public DataBase(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL(DATABASE_CREATE_SYNC);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
			onCreate(db);
		}
	}

	public DbHelper open() throws SQLiteException {

		help = new DataBase(mContext);
		mDb = help.getWritableDatabase();
		return this;
	}

	public void close() {
		help.close();
	}

	public long insertRecord(String syncId, String lastModified) {
		ContentValues values = new ContentValues();
		values.put(SYNC_ID, syncId);
		values.put(VALUE, lastModified);
		return mDb.insert(TABLE_NAME, null, values);
	}
	
	public long updateRecord(String syncId, String value)
	{
		ContentValues vr = new ContentValues();
		vr.put(VALUE, value);
		return mDb.update(TABLE_NAME, vr, SYNC_ID + "='" + syncId + "'",null);
	}
	
	public String getRecord(String syncId)
	{
		String time = "";
		Cursor c = mDb.query(TABLE_NAME, null,SYNC_ID + "='" + syncId + "'",null, null, null, null);
		if(c.moveToFirst())
		{
			time = c.getString(c.getColumnIndexOrThrow(VALUE));
		}
		OsyncUtil.close(c);
		return time;
	}

	public boolean deleteRecord(String syncId) {
		mDb.delete(TABLE_NAME, SYNC_ID + "='" + syncId + "'", null);
		return true;
	}

	public void deleteAllRecord() {
		mDb.execSQL("delete from " + TABLE_NAME + ";");
	}
	
	public void updateOrInsert(String syncId,String value)
	{
		if(TextUtils.isEmpty(getRecord(syncId)))
		{
			insertRecord(syncId, value);
		} else {
			updateRecord(syncId, value);
		}
	}
	
}